const app = getApp()
import {
    showMsg
} from '../../../utils/config.js'
import {
    reqDoorList,
    reqInfraredList,
    reqCommand,
    reqCameraGet,
    reqCameralogin,
    reqCameradeptList,
    reqCamerdeviceList,
    reqCamerurl
} from '../../../request/api'
Page({
    data: {
        playUrl: "https://1500005692.vod2.myqcloud.com/43843706vodtranscq1500005692/62656d94387702300542496289/v.f100240.m3u8",
        openDoor: false, //开门告警
        closeDoor: false, //关门告警
        height: '350rpx',
        navHeight: app.globalData.navHeight + 'px', //头部距离
        bottomHeight: app.globalData.bottomHeight + 'px', //iphone底部距离
        deviceInfo: {},
        dataList: [],
        page: 1,
        isNextPage: true, //是否下一页
        triggered: false, //是否下拉刷新列表
        srcFraredActive: '/statics/images/device/infrared_active.png',
        srcInfraredActive: '/statics/images/device/infrared_inactive.png',
        show: false,
        showStatus: false,
        showStatus2: false,
        serviceType: "work_mode",
        serviceValue: "0",
        serviceTypename: "工作模式",
        serviceValuename: "普通模式",
        src: "",
        username: "",
        password: "",
        access_token: "",
        deviceMac:"",
        openSound: true,
        accessToken:""
    },
    // onLoad(e) {
    //     // console.log(e.info);
    //     console.log(JSON.parse(e.info));
    //     let item =e.info
    //     this.setData({
    //           src:`http://192.168.1.111:8080/HomeView?deviceInfo=${item}`,
    //         // src:`${ app.globalData.videoUrl}/?sn=${opation.sn}`
    //     })
    // },
    async onLoad(e) {
        // console.log(e.info);
        console.log(JSON.parse(e.info));
        let item = JSON.parse(e.info)

        this.getDeviceInfo(e)
        // await this.CameraGet()
        // await this.Cameralogin()
        // await this.CamerdeviceList()
        // await this.Camerurl()

        this.gettoken()  // 获取token

    },
      // 获取token
      gettoken() {
        wx.request({
            url: `https://open.ys7.com/api/lapp/token/get`, //仅为示例，并非真实的接口地址
            method: 'POST',
            data: {
                appKey: 'd6a1a4287b9a4d78adebaa7bbc8c7125',
                appSecret: '6b9102e6b4ef80beb7067be13d08bd2c',
            },
            header: {
              'content-type': 'application/x-www-form-urlencoded' // 默认值
            },
            success: (res) => {
              console.log(res);
              this.setData({
                accessToken:res.data.data.accessToken
              })
              this.getaddress()//获取视频流
            }
          });
    },

    // 获取视频url
  async  getaddress(){
        wx.request({
            url: `https://open.ys7.com/api/lapp/v2/live/address/get`, //仅为示例，并非真实的接口地址
            method: 'POST',
            data: {
              accessToken: this.data.accessToken,
              deviceSerial: this.data.deviceInfo.imei,
              channelNo: 1,
              expireTime: 86400,
              quality: 2,
              protocol: 3,
            },
            header: {
              'content-type': 'application/x-www-form-urlencoded' // 默认值
            },
            success: (res) => {
                console.log(res);
              if(res.data.code!=200) return showMsg(res.data.msg)
              this.setData({
                playUrl:res.data.data.url
              })
            }
          });

          wx.createLivePlayerContext('livePlayer');

          await this.playHttpFlv()
    },
    fullscreenChange(event){
        console.log("监听到全屏变化", event)
      },

    statechange(e) {
        console.log('live-player code:', e)
    },
    error(e) {
        console.error('live-player error:', e)
      },
    onNetStatus() {},
    getLivePlayerContext(callback) {
        wx.createSelectorQuery().select('#livePlayerEle').context(function (res) {
            console.log(res.context) // 节点对应的 Context 对象。如：选中的节点是 <video> 组件，那么此处即返回 VideoContext 对象
            callback(res.context)
        }).exec();
    },
    playHttpFlv() {
        //     if (this.apiStartTime) this.printMsg('请求播放地址耗时：' + (Date.now() - this.apiStartTime))
        let url = this.data.playUrl;
        console.log(url);
        this.setData({
            playUrl: url,
        }, function () {
            this.playStartTime = Date.now();
            this.getLivePlayerContext((context) => {
                context.play({
                    success: () => {
                        console.log('发起连接');
                        this.printMsg('发起连接')
                    },
                    fail: this.error
                })
            })
        })
    },

    // 获取imei
    getDeviceInfo(e) {
        let item = JSON.parse(e.info)
        this.setData({
            deviceInfo: item
        })
        console.log(item);
        // this.getDataList()
    },
    // 停止云台控制
    bindtouchendFn(){
      wx.request({
        url: `https://open.ys7.com/api/lapp/device/ptz/stop`,
        method: 'POST',
        data: {
          accessToken: this.data.accessToken,
          deviceSerial: this.data.deviceInfo.imei,
          channelNo: 1,
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值
        },
        success: (res) => {
          console.log(res);
        }
      });
    },
    // 云台控制
    cloudControl(e){
      console.log(e.currentTarget.dataset.index);
      let direction
      if(e.currentTarget.dataset.index=='top'){
        direction=0
      }else  if(e.currentTarget.dataset.index=='right'){
        direction=3
      }else  if(e.currentTarget.dataset.index=='bottom'){
        direction=1
      }else  if(e.currentTarget.dataset.index=='left'){
        direction=2
      }
      wx.request({
        url: `https://open.ys7.com/api/lapp/device/ptz/start`,
        method: 'POST',
        data: {
          accessToken: this.data.accessToken,
          deviceSerial: this.data.deviceInfo.imei,
          channelNo: 1,
          direction: direction,
          speed: 1,
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值
        },
        success: (res) => {
          console.log(res);
        }
      });
    },
    async getDataList() {
        let params = {
            imei: this.data.deviceInfo.imei,
            spaceId: this.data.deviceInfo.spaceId
        }
        let {
            deviceType
        } = this.data.deviceInfo
        if (deviceType === "DoorMagnetism") {
            // 门磁
            const res = await reqDoorList(this.data.page, 10, params)
            if (res.code !== 20000) return showMsg(res.message)
            let {
                rows
            } = res.data
            if (this.data.page === 1) {
                this.setData({
                    dataList: rows,
                    isNextPage: true
                })
            } else if (this.data.page > 1 && rows.length) {
                this.setData({
                    dataList: this.data.dataList.concat(rows),
                    isNextPage: true
                })
            } else if (this.data.page > 1 && !rows.length) {
                showMsg('已经到底啦~')
                this.setData({
                    isNextPage: false
                })
            }
        } else if (deviceType === "Infrared") {
            // 红外
            const res = await reqInfraredList(this.data.page, 10, params)
            if (res.code !== 20000) return showMsg(res.message)
            let {
                rows
            } = res.data
            if (this.data.page === 1) {
                this.setData({
                    dataList: rows,
                    isNextPage: true
                })
            } else if (this.data.page > 1 && rows.length) {
                this.setData({
                    dataList: this.data.dataList.concat(rows),
                    isNextPage: true
                })
            } else if (this.data.page > 1 && !rows.length) {
                showMsg('已经到底啦~')
                this.setData({
                    isNextPage: false
                })
            }
        } else {
            return
        }
    },
   

   
})